/*
 * dacPacketHandler.h
 *
 * Created: 6/13/2013 3:01:33 AM
 *  Author: Tim
 */ 


#ifndef DACPACKETHANDLER_H_
#define DACPACKETHANDLER_H_

#include <inttypes.h>
#include "../../packets/status.h"
#include "../../communication/comPort.h"
#include "../../packets/structs/msgHeaderDefs.h"
#include "../../packets/structs/dacPacketStructs.h"
#include "../../packets/CRC.h"
#include "../../features/dac/dac.h"

static inline status_t dacInitWaveformHandler(dacInitWaveform_t *packet)
{
	
	tmrAlloc_t intTmr;
	uint16_t frequency;
	
	if(daqAlloc.standAlone.daqStandAlone) return OPP_FAILED;//this function is not standalone type
	
	frequency = (packet->PARAM3.DFRQH)<<8 | packet->PARAM5.DFRQL;
	
	//check for a timer with the same frequency
	intTmr = tmrCheckFrequency(frequency);	
	if(intTmr == TIMER_NULL)
	{
		//check to see if there is a free timer
		intTmr = tmrCheckAvailability();
		if(intTmr == TIMER_NULL) return OPP_FAILED;
		else
		{
			//before we alloc anything we need to make sure the table will be valid
			if (	dacWaveformTableInit(	packet->PARAM1.DCH,
											packet->PARAM1.WF,
											(packet->PARAM3.DFRQH<<8) | packet->PARAM5.DFRQL,
											(packet->PARAM3.DAMPH<<8) | packet->PARAM4.DAMPL,
											(packet->PARAM1.DOFFH<<8) | packet->PARAM2.DOFFL) == OPP_FAILED) return OPP_FAILED;
			
			//allocate the interrupt with the appropriate timer
			daqAlloc.dacCh_int[packet->PARAM1.DCH] = intTmr;
			
			//if the timer was free setup the frequency
			tmrSetupFreq(intTmr,frequency);
		}
	}
	else
	{
			//before we alloc anything we need to make sure the table will be valid
			if (	dacWaveformTableInit(	packet->PARAM1.DCH,
											packet->PARAM1.WF,
											(packet->PARAM3.DFRQH<<8) | packet->PARAM5.DFRQL,
											(packet->PARAM3.DAMPH<<8) | packet->PARAM4.DAMPL,
											(packet->PARAM1.DOFFH<<8) | packet->PARAM2.DOFFL) == OPP_FAILED) return OPP_FAILED;
		
			//allocate the interrupt with the appropriate timer
			daqAlloc.dacCh_int[packet->PARAM1.DCH] = intTmr;
	}
	
	return OPP_SUCCESSFUL;
}


static status_t dacUpdateHandler(dacUpdate_t *packet)
{
	
	if(daqAlloc.standAlone.daqStandAlone) return OPP_FAILED;//this function is not standalone type
	
	dacUpdate(	packet->PARAM1.DCHM,
	(packet->PARAM1.DVALH<<8) | packet->PARAM2.DVALL);
	
	return OPP_SUCCESSFUL;
}
#endif /* DACPACKETHANDLER_H_ */